package controllers.buy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.OrderItem;
import models.Product;

public class Cart extends ArrayList<OrderItem> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1351311317075267964L;
	private static Map<String, Cart> userCarts = new HashMap<String, Cart>();

	public static Cart getUserCart(String username) {

		Cart usercart = userCarts.get(username);
		if (null == usercart) {

			usercart = new Cart();
			userCarts.put(username, usercart);

		}
		return usercart;
	}

	private Cart() {
	}

	public void save(Product p, Integer amount) {

		for (OrderItem oi : this) {
			if (oi.getProduct().getName().equals(p.getName())) {
				oi.setAmount(oi.getAmount() + amount);
				return;
			}
		}

		OrderItem o = new OrderItem();
		o.setProduct(p);
		o.setAmount(amount);

		this.add(o);

	}

	public void setInCart(List<OrderItem> inCart) {
		this.clear();
		addAll(inCart);
	}

	public Integer getSummary() {
		Integer cash = 0;
		for (OrderItem item : this) {
			cash += item.getAmount() * item.getProduct().getPrice();
		}
		return cash;
	}
}
